package com.swt.agy.backend.utils;

/**
 * @author : wdn
 * @date : 2019-09-29 10:37
 */

import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FtpUtils {



    // ftp服务器地址

    public String hostname = "192.168.0.108";

    public Integer port = 21;

    // ftp登录账号
    public String username = "ag";

    // ftp登录密码

    private static final String showPath="";

    public String password = "1234567";

    public FTPClient ftpClient = null;

    private static final int BUFFER_SIZE = 1024000;

    private static String SERVER_CHARSET = "ISO-8859-1";

    private static String LOCAL_CHARSET = "GBK";


    private FileOutputStream fos = null;



    /**
     * 65 初始化ftp服务器
     */
    public void initFtpClient() {
        ftpClient = new FTPClient();
        /*  ftpClient.setControlEncoding("utf-8");*/
        try {
            ftpClient.connect(hostname, port); // 连接ftp服务器
            System.out.println("connecting...ftp服务器:" + this.hostname + ":" + this.port);
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);

            ftpClient.login(username, password); // 登录ftp服务器
            int replyCode = ftpClient.getReplyCode(); // 是否成功登录服务器
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("connect failed...ftp服务器:" + this.hostname + ":" + this.port);
            }
            System.out.println("connect successfu...ftp服务器:" + this.hostname + ":" + this.port);


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param file
     * @return
     */
    public boolean uploadFile(String pathname, String fileName, MultipartFile file) {
        boolean flag = false;
        InputStream inputStream = null;
        try {
            System.out.println("开始上传文件");
            // inputStream = new FileInputStream(new File(originfilename));
            inputStream = file.getInputStream();
            initFtpClient();
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            CreateDirecroty(pathname);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET), inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
            System.out.println("上传文件成功");
        } catch (Exception e) {
            System.out.println("上传文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public boolean upLoadFile2(MultipartFile file, String path, String fileName) throws IOException {
        boolean result = false;
        try {
            initFtpClient();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // make directory
            if (path != null && !"".equals(path.trim())) {
                String[] pathes = path.split("/");
                for (String onepath : pathes) {
                    if (onepath == null || "".equals(onepath.trim())) {
                        continue;
                    }
                    onepath = new String(onepath.getBytes("GBK"), "iso-8859-1");
                    if (!ftpClient.changeWorkingDirectory(onepath)) {
                        ftpClient.makeDirectory(onepath);
                        ftpClient.changeWorkingDirectory(onepath);
                        System.out.println(ftpClient.printWorkingDirectory());
                    }
                }
            }

            result = ftpClient.storeFile(new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET), file.getInputStream());

            /* result = ftpClient.storeFile(fileName, file.getInputStream());*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ftpClient.logout();
        }
        return result;
    }

    /**
     * 上传文件
     *
     * @param pathname       ftp服务保存地址
     * @param fileName       上传到ftp的文件名
     * @param originfilename 待上传文件的名称（绝对地址） *
     * @return
     */
    public boolean uploadFile(String pathname, String fileName, String originfilename) {
        boolean flag = false;
        InputStream inputStream = null;
        try {
            System.out.println("开始上传文件");
            inputStream = new FileInputStream(new File(originfilename));
            initFtpClient();
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            CreateDirecroty(pathname);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            ftpClient.logout();
            flag = true;
            System.out.println("上传文件成功");
        } catch (Exception e) {
            System.out.println("上传文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }


    // 改变目录路径
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                System.out.println("进入文件夹" + directory + " 成功！");

            } else {
                System.out.println("进入文件夹" + directory + " 失败！开始创建文件夹");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    // 创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
    public boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 如果远程目录不存在，则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    // 判断ftp服务器文件是否存在
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(new String(path.getBytes(LOCAL_CHARSET), SERVER_CHARSET));
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    // 创建目录
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                System.out.println("创建文件夹" + dir + " 成功！");

            } else {
                System.out.println("创建文件夹" + dir + " 失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * * 下载文件 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @return
     */
    public ResponseEntity<byte[]> downloadFile(String pathname, String filename) {
        boolean flag = false;
        OutputStream os = null;
        ResponseEntity<byte[]> entity = null;
        try {
            System.out.println("开始下载文件");
            initFtpClient();
            // 切换FTP目录
            pathname = new String(pathname.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.enterLocalPassiveMode();

            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    InputStream inputStream = ftpClient.retrieveFileStream(new String(filename.getBytes(LOCAL_CHARSET),SERVER_CHARSET) );
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentDispositionFormData("attachment", filename);
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    HttpStatus status = HttpStatus.OK;
                    //返回字节流IOUtils.toByteArray(in)
                    entity  = new ResponseEntity<byte[]>(IOUtils.toByteArray(inputStream), headers, status);
                /*    File localFile = new File(localpath + "/" + file.getName());
                    os = new FileOutputStream(localFile);*/
                   /* FileSystemView fsv = FileSystemView.getFileSystemView();
                    os = new FileOutputStream(fsv.getHomeDirectory()+"/"+filename);
                    System.out.println(fsv.getHomeDirectory()+"/"+filename);
                    ftpClient.setBufferSize(1024);*/
                  /*  ftpClient.retrieveFile(new String(file.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET), os);
                    os.close();*/
                }
            }
            ftpClient.logout();
            flag = true;
            System.out.println("下载文件成功");
        } catch (Exception e) {
            System.out.println("下载文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entity;
    }


    public long getFileSize(String pathname, String filename) {
        long fileSize = -1L;
        OutputStream os = null;
        try {
            System.out.println("开始获取文件大小");
            initFtpClient();
            // 切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    fileSize = file.getSize();
                }
            }
            ftpClient.logout();
            System.out.println("获取文件大小为:" + fileSize);
        } catch (Exception e) {
            System.out.println("获取文件大小失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileSize;
    }


    public boolean deleteFile(String fileurl) {
        boolean flag = false;
        String pathname = fileurl.substring(0, fileurl.lastIndexOf("/"));
        String filename = fileurl.substring(fileurl.lastIndexOf("/") + 1);
        try {
            System.out.println("开始删除文件");
            initFtpClient();
            // 切换FTP目录
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(new String(pathname.getBytes(LOCAL_CHARSET), SERVER_CHARSET));
            String s = ftpClient.printWorkingDirectory();
            int dele = ftpClient.dele(new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET));
            if (dele == 550) {
                flag = false;
            } else if (dele == 250) {
                flag = true;
            }
            ftpClient.logout();

            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /**
     * 递归遍历出目录下面所有文件
     *
     * @param pathName 需要遍历的目录，必须以"/"开始和结束
     * @throws IOException
     */
    public List<Map> List(String pathName) throws IOException {
        List<Map> re = new ArrayList<>();
        StringBuffer filename = new StringBuffer();
        initFtpClient();
        String preBase;
        if (pathName.startsWith("/") && pathName.endsWith("/")) {
            String directory = new String(pathName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
//更换目录到当前目录
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.changeWorkingDirectory(directory);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] files = ftpClient.listFiles();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].isFile()) {
                        String n = files[i].getName();
                        System.out.println(n + "fileName");
                        String fileName = new String(n.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
                        InputStream inputStream = ftpClient.retrieveFileStream(fileName);
                        if (inputStream != null) {
                            byte[] data = IOUtils.toByteArray(inputStream);
                            BASE64Encoder encoder = new BASE64Encoder();
                            preBase = "data:image/" + n.substring(n.lastIndexOf(".") + 1).toLowerCase() + ";base64,";
                            Map<String, String> map = new HashMap<>();
                            map.put("fileName", n);
                            map.put("base64", preBase + encoder.encode(data));
                            re.add(map);

                        }
                        inputStream.close();
                        ftpClient.completePendingCommand();
                    }
                }
            }
        }
        return re;
    }

    public boolean hasFile(String filePath) {
        boolean flag = false;
        try {

            initFtpClient();
            // 设置文件类型为二进制，与ASCII有区别
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            // 设置编码格式
            ftpClient.setControlEncoding("GBK");

            // 提取绝对地址的目录以及文件名
            String dir = filePath.substring(0, filePath.lastIndexOf("/"));
            String file = filePath.substring(filePath.lastIndexOf("/") + 1);

            // 进入文件所在目录，注意编码格式，以能够正确识别中文目录
            ftpClient.changeWorkingDirectory(new String(dir.getBytes("GBK"), ftpClient.DEFAULT_CONTROL_ENCODING));

            // 检验文件是否存在
            InputStream is = ftpClient
                    .retrieveFileStream(new String(file.getBytes("GBK"), ftpClient.DEFAULT_CONTROL_ENCODING));
            if (is == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
                return false;
            }

            if (is != null) {
                is.close();
                ftpClient.completePendingCommand();
            }
            return true;

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    public InputStream getInputStream(String path) throws UnsupportedEncodingException {
        byte[] bytes = null;
        path = new String(path.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
        InputStream in = null;
        try {
            initFtpClient();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            // 转到指定下载目录
            if (path != null) {// 验证是否有该文件夹，有就转到，没有创建后转到该目录下
                ftpClient.changeWorkingDirectory(path);// 转到指定目录下
            }
            // 不需要遍历，改为直接用文件名取
            String remoteAbsoluteFile = toFtpFilename(path);

            // 下载文件
            ftpClient.setBufferSize(1024 * 1024);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            in = ftpClient.retrieveFileStream(remoteAbsoluteFile);
            /*
             * bytes = input2byte(in); System.out.println("下载成功!" + bytes.length); //
             * in.read(bytes); in.close();
             */
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return in;
    }

    /**
     * 文件转成 byte[]
     *
     * @param inStream
     * @return
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[inStream.available()];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        swapStream.close();
        return in2b;
    }

    /**
     * 转化输出的编码
     */
    private static String toFtpFilename(String fileName) throws Exception {
        return new String(fileName.getBytes("UTF-8"), "ISO8859-1");
    }


    // 判断是否是目录
    public boolean isDir(String fileName) {
        try {
// 切换目录，若当前是目录则返回true,否则返回true。
            boolean falg = ftpClient.changeWorkingDirectory(new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET));
            return falg;
        } catch (Exception e) {
            e.printStackTrace();

        }

        return false;
    }


    public void downloadFiles(String remoteFileName, String localPath) throws IOException {
        remoteFileName = new String(remoteFileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
// 转移到FTP服务器目录
        initFtpClient();
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ftpClient.changeWorkingDirectory(remoteFileName);
        FTPFile[] fs = ftpClient.listFiles();
        for (FTPFile ff : fs) {

            if (ff.isDirectory()) {

                downloadFiles(remoteFileName + "/" + ff.getName(), localPath + "/" + ff.getName());

            } else {

                File localFile = new File(localPath + "/" + ff.getName());

                if (!localFile.getParentFile().exists()) {

                    localFile.getParentFile().mkdirs();

                }

                OutputStream os = new FileOutputStream(localFile);

                ftpClient.retrieveFile(new String(ff.getName().getBytes(LOCAL_CHARSET), SERVER_CHARSET), os);

                /*   map.put(ff.getName(), ff.getSize() + ""); // 放数据*/


                os.close();

            }

        }
    }

    public Boolean createDir(String dirname) throws UnsupportedEncodingException {
        Boolean re = false;
        dirname = new String(dirname.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
        initFtpClient();
        try {

            re = ftpClient.makeDirectory(dirname);

            System.out.println("在目标服务器上成功建立了文件夹: " + dirname);

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        }
        return re;
    }


    public void copyFile( String sourceDir,String sourceFileName, String targetDir) throws IOException {
        ByteArrayInputStream in = null;
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        try {
            initFtpClient();
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            ftpClient.setControlEncoding(LOCAL_CHARSET);
            // 创建目录
            createDirectory(ftpClient, targetDir);
            ftpClient.setBufferSize(1024 * 2);
            // 变更工作路径
            ftpClient.changeWorkingDirectory(sourceDir);
            // 设置以二进制流的方式传输
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            // 将文件读到内存中
            ftpClient.retrieveFile( new String(sourceFileName.getBytes(LOCAL_CHARSET), "iso-8859-1"), fos);
            in = new ByteArrayInputStream(fos.toByteArray());
            if (in != null) {
                ftpClient.changeWorkingDirectory(targetDir);
                String sbstring = sourceFileName;
                StringBuilder sb = new StringBuilder(sbstring);// 构造一个StringBuilder对象
                Date date = new Date();
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                sb.insert(sbstring.indexOf("."), "-"+sd.format(date));
                sourceFileName = ""+sb;
                ftpClient.storeFile(new String((targetDir).getBytes(LOCAL_CHARSET), "iso-8859-1"), in);

            }
        } finally {
            // 关闭流
            if (in != null) {
                in.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }


    // 创建目录
    private void createDirectory(FTPClient ftpClient, String targetDir) {
        targetDir = targetDir.substring(0, targetDir.lastIndexOf("/") + 1);
        try {
            if (!targetDir.equalsIgnoreCase("/")
                    && !ftpClient.changeWorkingDirectory(new String(targetDir.getBytes("GBK"), "iso-8859-1"))) {
                int[] position = { 0, 0 };
                if (targetDir.startsWith("/")) {
                    position[0] = 1;
                } else {
                    position[0] = 0;
                }
                position[1] = targetDir.indexOf("/", position[0]);
                while (true) {
                    String subDir = new String(targetDir.substring(position[0], position[1]).getBytes("GBK"),
                            "iso-8859-1");
                    if (!ftpClient.changeWorkingDirectory(subDir)) {
                        if (ftpClient.makeDirectory(subDir)) {
                            ftpClient.changeWorkingDirectory(subDir);
                        } else {
                            System.out.println("创建目录失败！");
                        }
                    }
                    position[0] = position[1] + 1;
                    position[1] = targetDir.indexOf("/", position[0]);
                    // 检查所有目录是否创建完毕
                    if (position[1] <= position[0]) {
                        break;
                    }
                }
            }

        } catch (Exception e) {
            System.out.println("复制文件失败！");
            e.printStackTrace();
        }
    }
/**
 *实现文件打包压缩下载
 * @param response  服务器响应对象HttpServletResponse
 * @param zipname 压缩包的文件名
 * @param ftpPath ftp文件路径
 * @param ftpFileList 要下载的文件名集合
 */
    public  Byte[] zipDownloadFile(HttpServletResponse response, String zipname, String ftpPath, List<String>ftpFileList) {
            initFtpClient();
        byte[] buf = new byte[1024];
        try {
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(LOCAL_CHARSET),SERVER_CHARSET));
            File zipFile = new File("123");
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i=0;i< ftpFileList.size();i++) {
                ZipEntry entry = new ZipEntry((i+1)+"_"+ftpFileList.get(i));
                zipOut.putNextEntry(entry);
                InputStream bis = ftpClient.retrieveFileStream(new String(ftpFileList.get(i).getBytes(LOCAL_CHARSET),SERVER_CHARSET));
                if (bis != null) {
                    int readLen = -1;
                    while ((readLen = bis.read(buf, 0, 1024)) != -1) {
                        zipOut.write(buf, 0, readLen);
                    }
                    zipOut.closeEntry();
                    bis.close();
                    ftpClient.completePendingCommand();
                    //调用ftp.retrieveFileStream这个接口后，一定要手动close掉返回的InputStream，然后再调用completePendingCommand方法
                    // ，若不是按照这个顺序，则会导致后面对FTPClient的操作都失败
                }
            }
            zipOut.close();
            ftpClient.logout();
            //下载
            int len;
            FileInputStream zipInput =new FileInputStream(zipFile);
            OutputStream out = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(zipname, "UTF-8") + ".zip");
            while ((len=zipInput.read(buf))!= -1){
                out.write(buf,0,len);
            }
            zipInput.close();
            out.flush();
            out.close();
            //删除压缩包
            zipFile.delete();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return new Byte[0];
    }

    public void uploadFile(String path,String flieName,File file){


        Ftp ftp = new Ftp(hostname, port, username, password, Charset.forName("GBK"), FtpMode.Passive);
        boolean success =   ftp.upload(path, flieName, file);
        log.info("upload = {}",success);
    }


    public void download(String path,File file){


        Ftp ftp = new Ftp(hostname, port, username, password, Charset.forName("GBK"), FtpMode.Passive);
        ftp.download(path,file);

    }


    public boolean deleteDir(String path){
        Ftp ftp = new Ftp(hostname, port, username, password, Charset.forName("GBK"), FtpMode.Passive);
        boolean flag = true;
        try {
            flag = ftp.delDir(path);
            if (flag) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    public boolean renameDir(String sourceDir,String targetDir) throws IOException {
        FTPClient ftpClient1 = new FTPClient();
        ftpClient1.connect(hostname,port);

        ftpClient1.changeWorkingDirectory(targetDir);
        ftpClient1.rename(sourceDir,targetDir);
        return true;
    }

    public boolean renameFile(String srcFname,String targetFname){

        boolean flag = false;
        if(ftpClient!=null ){
            try {
                flag = ftpClient.rename(srcFname,targetFname);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


}